import { Module } from '@nestjs/common';
import { APP_INTERCEPTOR } from '@nestjs/core';
import { AuthModule } from './modules/auth/auth.module';
import { ConfigModule, registerAs } from '@nestjs/config';
import { TransformInterceptor } from './interceptors/transform.interceptor';

export type BaseType = boolean | number | string | undefined | null;

function fromatValue<T extends BaseType = string>(
  key: string,
  defaultValue: T,
  callback?: (value: string) => T
): T {
  const value: string | undefined = process.env[key];
  if (typeof value === 'undefined') return defaultValue;

  if (!callback) return value as unknown as T;

  return callback(value);
}

export function env(key: string, defaultValue: string = ''): string {
  return fromatValue(key, defaultValue);
}

@Module({
  imports: [
    ConfigModule.forRoot({
      isGlobal: true,
      expandVariables: true,
      load: [
        // 注意这里，把结果放进数组中
        registerAs('app', () => ({
          globalPrefix: env('GLOBAL_PREFIX', 'api')
        }))
      ]
    }),
    AuthModule
  ],
  providers: [{ provide: APP_INTERCEPTOR, useClass: TransformInterceptor }]
})
export class AppModule {}
